<template>
  <basic-container>
    <div style="width:100%;min-height: 50px;padding-left:5px;display: inline-block;margin-bottom: 20px">
      <el-container>
        <el-container>
          <el-container>
            <el-main style="background: #fff!important">
              <div style="background:#fff;height: 50px;line-height: 50px;padding-left:5px ">
                产线模板名称：<avue-input v-model="lineName" style="width:180px;margin-right: 5px" placeholder="请输入产线模板名称" ></avue-input>
                <el-button type="primary" @click="saveRealityLineTpl">保存</el-button>
              </div>
            </el-main>
          </el-container>
        </el-container>
      </el-container>
    </div>
    <template>
      <div class="form-designer"  v-loading="saveLoading">
        <el-container style="border: #e0e0e0 solid 1px;border-top:none">
          <el-aside width="240px">
            <el-header style="z-index:100;height:50px;text-align: center;line-height: 50px;width:240px;position: absolute;background: #fff">工位</el-header>
            <div style="height:800px;margin-top:45px">
              <!--工位菜单-->
              <workPositionMenu/>
            </div>
          </el-aside>
          <el-main class="demo" style="border-left: 1px solid #e0e0e0;">
            <avue-flow :height="800"
                       width="100%"
                       style="min-height: 800px;"
                       ref="flow"
                       :option="option"
                       v-model="flowForm">
              <template #header="{node}" >
                  <el-tooltip class="item" effect="dark" :content="`工位(`+(node || {}).name+`)`" placement="top-start">
                     <span style="width:145px;white-space: nowrap;overflow: hidden;display: inline-block;vertical-align: bottom;text-overflow: ellipsis;">
                        工位({{(node || {}).name}})
                    </span>
                  </el-tooltip>
                  <div style="float: right;margin-right: 5px">
                    <el-tooltip class="item" effect="dark" content="添加工序" placement="top">
                      <i class="el-icon-plus" @click="openProcessDialog(node)" style="cursor: pointer;font-size:13px;margin-top: -2px;color:#403f3f;"></i>
                    </el-tooltip>
                    <el-divider direction="vertical"></el-divider>
                    <el-tooltip class="item" effect="dark" content="删除工序" placement="top-start">
                        <i class="el-icon-delete"  style="cursor: pointer;line-height: 30px;" @click="deleteNode(node)"></i>
                    </el-tooltip>
                </div>
              </template>
              <template slot-scope="{node}">
                 <el-collapse :ref="node.id+`Ref`"  v-model="showActive[node.id]" :style="{width:'100%',zIndex:zIndexStyle}"  @mouseover.native="handleMouseEnter(node.id)"  @mouseout.native="handleMouseLeave(node.id)">
                  <el-collapse-item title="工序信息" name="1">
                    <el-descriptions  class="margin-top"  style="width: 100%;" title="" :column="1" size="small" border >
                        <el-descriptions-item  label="工序" :labelStyle="{'width': '50px'}"
                          v-model="`process_`+node.id"
                          v-for="(item, index) in workPositionProcessItem[node.id]">

                          {{item.processName}}

                        </el-descriptions-item>
                    </el-descriptions>
                  </el-collapse-item>
                 </el-collapse>
              </template>
            </avue-flow>

          </el-main>
        </el-container>
      </div>
    </template>

    <!--工序添加弹窗页面-->
    <el-dialog title=""
               :visible.sync="addProcessDialogVisible"
               width="50%"
               height="600"
               lock-scroll
               v-dialogDrag
               append-to-body
               :close-on-click-modal="false"
               v-if="addProcessDialogVisible"
               :fullscreen="addProcessDialogFull">
      <el-backtop target=".el-card__body .el-dialog__wrapper .el-dialog" :right="15" :bottom="20" :visibility-height="1" />
      <el-backtop :bottom="60"></el-backtop>
      <template slot="title">
        <div class="avue-crud__dialog__header">
          <span class="el-dialog__title">
              <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
              {{workPositionName}}-工序信息
          </span>
          <div class="avue-crud__dialog__menu" style="cursor: pointer;margin-top: -2px;margin-right: 10px;" @click="addProcessDialogFull? addProcessDialogFull=false: addProcessDialogFull=true">
              <i class="el-icon-full-screen"></i>
          </div>
        </div>
      </template>
      <!--工序菜单-->
      <div style="width: 100vh;display: inline-block;margin-top: 10px;margin-bottom: 10px">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText" style="width:60vh;float:left;"></el-input>
        <el-button type="primary" @click="getCheckedProcess" style="float:left;margin-left: 10px">确认</el-button>
      </div>
      <el-tree
        ref="processTree"
        class="filter-tree el-dialog-height"
        :data="processTree"
        :props="processProps"
        node-key="id"
        show-checkbox
        check-strictly
        check-on-click-node
        :filter-node-method="filterNode"
        >
      </el-tree>
    </el-dialog>

  </basic-container>
</template>

<script>
import {fetchMenuTree} from "@/api/pfoc/pfocprocess";
import {saveLineTpl} from '@/api/pfoc/realityproductlinetemplate'
import workPositionMenu from '@/views/pfoc/workposition/workPosition-menu'

export default {
        name: "add-line-tpl",
        components: {
          workPositionMenu,
        },
        provide() {
          return {
            workPositionAddThis: this
          }
        },
        data() {
            return {
                count: 0,
                flowForm:'',
                nodeCount:0,//节点下标
                form: [],//提交时数据集合
                processTree:[],//工序集合
                coveringJson:[],//节点删除后补位集合
                workPositionProcessItem: {},//存储工位对应工序的二位数组
                processProps:{
                     id: 'id',
                     label: 'label',
                     children: 'children',
                     disabled: function (data, node) {//带子级的节点不能选中
                        if(data.processType !== '1') {
                          return true
                        } else {
                          return false
                        }
                      }
                },
                filterText: '',//过滤
                option: {
                    name: null,
                    nodeList: [],//工位节点集合
                    lineList: [],//工位各节点指向顺序集合
                },
                lineName:null,//产线模板名称
                saveLoading:false,//保存时遮罩开关
                addProcessDialogVisible:false,//工序添加弹窗开关
                addProcessDialogFull:false,//工序添加弹窗放大缩小
                workPositionName:null,//工位名称(用于工序添加)
                workPositionId:null,//工位ID(用于工序添加)
                nodeId:null,//工位节点ID(用于工序添加)
                zIndexStyle:"",
                showActive:[],//属性展示model集合
            };
        },
        watch: {
          filterText(val) {
            this.$refs.processTree.filter(val);
          }
        },
        created() {
           //获取工序
            this.getMenuTree();
        },
        computed: {
            nodeList () {
                return this.option.nodeList
            }
        },
        mounted() {
            this.nodeCount = this.option.nodeList.length;//初始化节点下标
        },
        methods: {
            /**打开添加工序窗口*/
            openProcessDialog(node){
                this.addProcessDialogVisible=true;
                this.workPositionName = node.name;
                this.workPositionId = node.mark;
                this.nodeId = node.id;
                const checkedNodes = this.workPositionProcessItem[node.id];
                if(!this.validatenull(checkedNodes)) {
                  //设置反显
                  this.$nextTick(() => {
                    this.$refs.processTree.setCheckedNodes(this.workPositionProcessItem[node.id]);
                  });
                }
            },
            //搜索过滤节点
            filterNode(value, data) {
              if (!value) return true;
              return data.label.indexOf(value) !== -1;
            },
            //存储选中的工序放入集合
            getCheckedProcess() {
              const checkedNodes = this.$refs.processTree.getCheckedNodes();
              var arry =[];
              for (var i = 0; i < checkedNodes.length; i++) {
                var obj = {};
                obj.id = checkedNodes[i].id; // 工序ID
                obj.label = checkedNodes[i].label; // 工序名称
                obj.processName = checkedNodes[i].processName;//工序名称
                obj.workshopSection = checkedNodes[i].workshopSection; // 工序所属工段
                arry.push(obj);
              }
              this.$set(this.workPositionProcessItem, this.nodeId, arry);//添加工序集合
              this.$set(this.showActive, this.nodeId, ['1']);//添加属性展示
              this.addProcessDialogVisible = false;//关闭工序添加弹窗
            },
            /**获取工序*/
           getMenuTree() {
              this.loading = true
              fetchMenuTree(this.queryParams).then(response => {
                this.processTree = response.data.data
              })
            },
           /* /!**添加工位*!/
            addWorkPositionNode(name,id){//工位名称，工位ID
                var left = 0;
                let isIncreasing = false;
                var color;
                if ((parseInt(this.nodeCount / 4))%2===0){
                  left = (this.nodeCount % 4)*300
                  isIncreasing = true; // 表示 left 正在增加
                }else {
                  left = ((3-this.nodeCount % 4)*300)
                  isIncreasing = false; // 表示 left 正在减少
                }
                var top = parseInt(this.nodeCount / 4)*150

                // 判断 top 是奇数行还是偶数行
                var row = parseInt(this.nodeCount / 4);
                var isEvenRow = row % 2 === 0;
                var remainder = this.nodeCount % 4;
                // 判断 remainder 是否为 0
                var isDivisibleByFour = remainder === 0;
                if (isDivisibleByFour) {
                    color = isEvenRow ? 'red' : 'blue';
                } else {
                    color = isIncreasing ? 'green' : 'orange';
                }
                this.$refs.flow.addNode(name,id,this.nodeCount,left,top);//添加节点
                //画线
                if(this.nodeList.length>1) {
                  var t = this;
                  var index = this.nodeList.findIndex(item => item.id === "node"+t.nodeCount);
                  var from = this.nodeList[index - 1].id;
                  var to = this.nodeList[index].id;
                  this.$nextTick((function() {
                    this.$refs.flow.drawLines({"from": from, "to": to},color)
                  }));
                }
              this.nodeCount=this.nodeCount+1;//更新节点下标
            },*/
          addWorkPositionNode(name,id){//工艺名称，工艺ID
              if (this.coveringJson.length > 0) {
                // 提醒是否按顺序补位
                this.$confirm('是否按顺序补位?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.addNodeFromCoveringJson(name, id);
                }).catch(() => {
                  this.addNodeManually(name, id);
                });
              } else {
                this.addNodeManually(name, id);
              }
            },
            addNodeFromCoveringJson(name, id) {
              // 需要补位，则每次取出补位集合第一个数据进行补位
              const node = this.coveringJson.shift(); // 移除并返回第一个元素
              const nodeId = node.id;
              const nodeIdNum = parseInt(nodeId.replace(/\D/g, ''), 10); // 提取数字并转换为整数
              // 添加节点
              this.$refs.flow.addNode(name, id, nodeIdNum, node.left, node.top);
              // 画线
              this.drawLinesFromPrevious(nodeIdNum);
              this.drawLinesToNext(nodeIdNum);
            },

            addNodeManually(name, id) {
              let left = 0;
              if ((parseInt(this.nodeCount / 4)) % 2 === 0) {
                left = (this.nodeCount % 4) * 300;
              } else {
                left = ((3 - this.nodeCount % 4) * 300);
              }
              const top = parseInt(this.nodeCount / 4) * 150;
              // 添加节点
              this.$refs.flow.addNode(name, id, this.nodeCount, left, top);
              // 画线
              this.drawLinesFromPrevious(this.nodeCount);
              // 更新节点下标
              this.nodeCount += 1;
            },
            drawLinesFromPrevious(nodeIdNum) {
              const t = this;
              // 从上一个节点到当前节点
              if (t.nodeList.length > 1) {
                const from = `node${nodeIdNum - 1}`;
                const to = `node${nodeIdNum}`;
                t.$nextTick(() => t.$refs.flow.drawLines({ from, to }));
              }
            },
            drawLinesToNext(nodeIdNum) {
              const t = this;
              console.log(t.nodeList)
              // 从当前节点到下一个节点
              if (t.nodeList.length-1 !== nodeIdNum) {
                const from = `node${nodeIdNum}`;
                const to = `node${nodeIdNum + 1}`;
                t.$nextTick(() => t.$refs.flow.drawLines({ from, to }));
              }
            },
            /**删除工位*/
            deleteNode(node){
                var id = node.id;
                var t = this;
                this.$confirm("确定要删除工位" + node.name + "?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                    closeOnClickModal: !1
                }).then((function() {
                    t.$refs.flow.deleteNode(id);
                    t.$delete(t.workPositionProcessItem, id); // 删除 workPositionProcessItem 中对应的节点
                    let coveringNode = { ...node }
                    t.coveringJson.push(coveringNode);
                    //补位集合中的数据顺序按照nodeId重新排序
                    t.coveringJson.sort((a, b) => parseInt(a.id.replace(/\D/g, ''), 10) - parseInt(b.id.replace(/\D/g, ''), 10));
                })).catch((function() {}))
            },

            /**保存产线*/
            saveRealityLineTpl(){
                if(this.validatenull(this.lineName)){
                    this.$message.warning("产线模板名称不能为空。")
                    return;
                }
                if(this.validatenull(this.option.nodeList)){
                    this.$message.warning("请选择工位制定产线模板。")
                    return;
                }
                //组装需要提交的数据
                var params = {};//参数集合
                params.lineName = this.lineName;//产线模板名称
                params.processNodes = JSON.stringify(this.option.nodeList);//工位节点集合（其中mark字段为工位ID）
                params.processNodeLine = JSON.stringify(this.option.lineList);//工位各节点指向顺序集合
                params.coveringJson = JSON.stringify(this.coveringJson);//节点补位集合

              //组装需要提交的数据-子表数据组装
                var objArr = [];
                for(var i=0;i<this.option.nodeList.length;i++){
                  var obj = {};//创建对象
                  var nodeId = this.option.nodeList[i].id;
                  var nodeObj = this.option.nodeList[i]
                  obj['workPositionId'] = nodeObj.mark;//取出工位ID加入对象
                  obj['workPositionName'] = nodeObj.name;//取出工位名称加入对象
                  obj['nodeId'] = nodeObj.id;
                  var workPositionProcessItem = this.workPositionProcessItem[nodeId];
                  if(this.validatenull(workPositionProcessItem)){
                    this.$message.warning("请为工位【"+nodeObj.name+"】配置工序。");
                    return;
                  }
                  obj['workPositionProcessItem'] = JSON.stringify(workPositionProcessItem);//取出工位配置的工序集合加入对象
                  var processNameStr="";//工序名字符串
                  var processIdStr="";//工序ID字符串
                  for (let j = 0; j < workPositionProcessItem.length; j++) {
                      processNameStr = processNameStr + workPositionProcessItem[j].processName + ",";
                      processIdStr = processIdStr + workPositionProcessItem[j].id + ",";
                  }
                  obj['processNameStr'] = processNameStr.substring(0,processNameStr.length-1);
                  obj['processIdStr'] = processIdStr.substring(0,processIdStr.length-1);
                  objArr.push(obj);
                }
                this.saveLoading=true;
               var data={
                  lineTpl:params,
                  lineTplDetails:objArr,
                }
                //提交
                saveLineTpl(data).then(response => {
                    if(response.data.data=="1") {
                        this.$message.warning(
                            {
                                message: "新增产线模板失败，产线：【"+this.lineName+"】已存在，已勿重复添加。",
                                duration: 5000 // 设置时长为5秒
                            });
                        this.saveLoading = false;
                    }else{
                        this.$message.success("产线模板添加成功。")
                        this.saveLoading = false;
                        this.$emit('closeTplAdd');//关闭新增页面
                    }
                }).catch(() => {
                    this.saveLoading = false;
                });
            },
            //鼠标移到置顶
            handleMouseEnter(nodeId) {
                //属性鼠标移到展开
                // this.$set(this.showActive, nodeId, ['1']);
                let ref = nodeId+"Ref";//获取到当前的ref
                this.$refs[ref].$parent.$refs.node.style.zIndex="999999";
                this.zIndexStyle="1";

            },
            //鼠标移开取消置顶
            handleMouseLeave(nodeId) {
                //属性鼠标移开关闭
                // this.$set(this.showActive, nodeId, []);
                let ref = nodeId+"Ref";//获取到当前的ref
                this.$refs[ref].$parent.$refs.node.style.zIndex="2";
                this.zIndexStyle="";
            },

        }
    };
</script>

<style scoped>
  /deep/.avue-flow__node{
    height: auto!important;
  }
  /deep/ .avue-flow__node-header {
    line-height: 40px;
  }
  /deep/.el-descriptions__title {
    font-size: 14px;
    font-weight: 400;
    margin-top: 5px;
  }
  /deep/.el-divider--vertical{
    background-color:#403f3f;
    margin-top: -1px;
  }
 /deep/ .el-dialog-height {
    height: 60vh;
    overflow: auto;
   /* 隐藏默认的滚动条样式 */
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */
}
  /*以下样式是打印的时候avue表格错乱修正方式（主要是序号列和操作列固定影响的）*/
  /deep/.el-table__fixed{
    display: none!important;
  }
  /deep/.el-table__fixed-right{
    display: none!important;
  }
  /deep/.el-table__cell.is-hidden>*{visibility:visible !important;}

  /deep/ .avue-grid{
    display: none!important;
  }
  /deep/.el-main{
    background:#fff !important;
  }
  /deep/.el-card__body{
    padding: 0px!important;
  }
  /*去掉滚动条样式*/
  .demo::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }
  .demo {
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-x: hidden;
    overflow-y: auto;
  }
</style>
